import moment from "moment";

export default {
	pubConfig() {
		let d = {
			apiUrl: 'https://sq.bcwhkj.cn/api/v2.' //API地址
		}
		return d;
	},
	dd() {
		console.log("调用公众JS成功！")
	},
	ss() {

		let that = this;
		console.log('api:', that.$json.apiUrl);
	},
	GoBack() {
		uni.navigateBack({
			delta: 1
		});
	},
	Now() {
		return moment().get('year') + '-' +
			(moment().get('month') + 1) + '-' +
			moment().get('date') + ' ' +
			moment().get('hour') + ':' +
			moment().get('minute') + ':' +
			moment().get('second');
	},
	/**
	 * @return 是否是建行生活APP
	 */
	isJianHangApp() {
		//#ifdef H5 
		if (navigator.userAgent.indexOf('CloudMercWebView') > 0) {
			console.log('在建行生活APP内');
			return true;
		} else {
			console.log('非建行生活APP');
			return false;
		}
		//#endif
	},
	isWeChat() {
		//#ifdef H5 
		if (navigator.userAgent.indexOf('wechat') > 0) {
			console.log('在微信 APP内');
			return true;
		} else {
			console.log('非微信 APP内');
			return false;
		}
		//#endif
	},
	isAndroid() { //判断是否为安卓
		//#ifdef H5 
		var e = navigator.userAgent.toLowerCase();
		var n = /Android/i.test(e);
		console.log(n ? '是安卓' : '不是安卓');
		return n
		//#endif
	},
	logins(callback) {
		uni.login({
			provider: 'weixin', //使用微信登录
			success: function(loginRes) {
				uni.showLoading({});
				console.log(loginRes.code);
				let postD = {
					code: loginRes.code
				}
				that.pubjs.postUrl('Xiaocx/getUserInfoOpenid', JSON.stringify(postD),
					function(e) {
						console.log(e);
						uni.hideLoading();
						if (e.codes == 200 || e.codes == 304) {
							uni.setStorageSync('token', e.data.token);
							uni.setStorageSync('openid', e.data.openid);
							//that.pubjs.goUrl('/pages/Mall/OrderInfo/OrderInfo',0);
							callback();
						} else {
							uni.showToast({
								title: e.mess
							})
						}
					}, '公共模块：获取openid')
			}
		});
	},
	isIphone() { //判断是否为苹果

		//#ifdef H5 
		var e = navigator.userAgent.toLowerCase();
		var t = /iPhone|iPad|iPod/i.test(e);
		console.log(t ? '是苹果' : '不是苹果');
		return t
		//#endif
	},
	/**
	 * return 登陆检测
	 */
	checkToken(callback) {
		console.log('检测登陆状态');

		if (uni.getStorageSync('openid')) {

			console.log('有openid')

			let postD = {
				// openid:getQV('openid'),
				// nickname:getQV('nickname'),
				// headimgurl:getQV('headimgurl'),
			}
			this.postUrl('/api/v2.Login/register', postD, function(e) {
				if (e.codes == 500) {

					//#ifdef H5 
					location.href = 'close.html';
					//#endif
					return false;
				}
				//layer.msg('登陆成功');
				localStorage.id = e.data.cxid;
				localStorage.username = e.data.cxusername;
				localStorage.token = e.data.cxtoken;
				localStorage.level = e.data.cxuserlevel;
				localStorage.img = e.data.cximg0;
				localStorage.name = e.data.cxfullname;
				localStorage.lastlogintime = e.data.cxlastlogintime;
				localStorage.sortid = e.data.cxsortid;
				//#ifdef H5 
				location.href = '/';
				//#endif
				callback();
			});

		} else {
			let that = this;
			that.postUrl('Login/checklogin', {
				token: uni.getStorageSync('token')
			}, function(e) {
				if (e.codes == 200) {
					uni.setStorageSync('id', e.data.id);
					uni.setStorageSync('img', e.data.img);
					uni.setStorageSync('level', e.data.level);
					uni.setStorageSync('name', e.data.name);
					uni.setStorageSync('username', e.data.username);
					uni.setStorageSync('token', e.data.token);
					console.log('TOKEN验证通过，身份正常');
					callback();
				} else {
					console.log('验证不通过');
					uni.showToast({
						title: e.mess,
						duration: 2000
					})
					uni.clearStorageSync();
					setTimeout(function() {
						that.goUrl('/pages/public/login', 0);
					}, 2000)
					return false;
				}

			}, 'TOKEN验证');
		}
	},
	postUrl(urls, postD, callback, title = '') {
		let that = this;
		let apiServer = this.pubConfig().apiUrl;
		if (!urls.includes('http')) {
			urls = apiServer + urls;
		}
		uni.request({
			url: urls,
			data: postD,
			method: 'POST',
			header: {
				'content-type': "application/x-www-form-urlencoded"
			},
			complete: (res) => {
				res = res.data;
				console.log('%cpostUrl - ' + title, 'background-color:green;padding:3px;color:#fff', '返回:',
					res, '路径:' + urls, '提交的数据', postD);
				callback(res);


			},
			fail: (res) => {
				uni.showToast({
					title: '请求接口失败！ - ' + title
				})
				callback(res);
			}
		});
	},
	goUrl(urls, types = 0) {
		console.log('触发跳转')
		//urls:跳转地址
		//types: 0或空默认，1为redirectTo跳转（不保留原页面）
		var key = 0;
		// console.log("接收到URL地址："+urls);
		if (urls == "/pages/index/index" || urls.indexOf("pages/index/index?") != -1) {
			key = 1;
		}
		//if (urls=="/pages/category/categoryPro" || urls.indexOf("pages/category/categoryPro?")!=-1) {key=1;}
		if (urls == "/pages/other/ruYuan" || urls.indexOf("pages/other/ruYuan") != -1) {
			key = 1;
		}
		if (urls == "/pages/user/user" || urls.indexOf("pages/user/user?") != -1) {
			key = 1;
		}
		// if (urls.indexOf("public/user")!=-1) {key=1;}
		if (key == 1) {
			console.log("跳转tabBar页面：" + urls);
			// uni.reLaunch({
			//     url: urls
			// });
			uni.switchTab({
				url: urls,
				success: function() {
					// console.log("成功跳转");
				},
				fail: function(e) {
					console.log("跳转失败：" + JSON.stringify(e));

				}
			});
		} else {
			if (types == 1) {
				console.log("redirectTo跳转页面：" + urls);

				uni.redirectTo({
					url: urls,
					success: function() {
						// console.log("成功跳转");
					},
					fail: function(e) {
						console.log("跳转失败：" + JSON.stringify(e));
					}
				});

			} else {

				console.log("navigateTo跳转页面：" + urls);

				uni.navigateTo({
					url: urls,
					success: function() {
						// console.log("成功跳转");
					},
					fail: function(e) {
						console.log("跳转失败：" + JSON.stringify(e));
					}
				});
			}
		}

	},

	//获取Strorage
	getKey(keyName) {
		uni.getStorage({
			key: keyName,
			complete: function(res) {
				console.log("获取Key:" + res.data);
			}
		});
	},

	// 保存图片到手机
	//@longpress="saveImg(Imgitem)"; //长按事件
	saveImg(urlimg) {
		uni.downloadFile({ //下载图片
			url: urlimg,
			success: (res1) => {
				uni.saveImageToPhotosAlbum({ //将图片保存在手机
					filePath: res1.tempFilePath, //保存的位置
					success: (res3) => {

						if (res3.errMsg == "saveImageToPhotosAlbum:ok") {
							uni.showToast({
								title: '保存图片成功',
								icon: "none"
							});
						} else {
							uni.showToast({
								title: '保存图片失败',
								icon: "none"
							});
						}

					}
				});
			}
		})

	},
	//确定时 当前页面刷新 
	showModalsReload(content, title = '提示') {
		uni.showModal({
			title: title,
			content: content,
			showCancel: true,
			success: function(res) {
				if (res.confirm) {
					window.location.reload();
				} else if (res.cancel) {
					console.log('用户点击取消');
				}

			}
		});
	},
	goPageDown() {
		var timer = setTimeout(function() {
			console.log("移到页面最下面");
			uni.pageScrollTo({
				scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
				duration: 200
			});
		}, 1000);
	},
	//
	/**
	 * @return js 格式化日期，去掉里面的-和：
	 */
	dgFormData(e) {

		const formattedDate = e.replace(/[-:]/g, '')

		return formattedDate;
	}
	// bcJiSuan(a,operation,b){
	// 	let that=this;
	//     //高精度数字函数

	//     if(a==0 && b==0){return 0;}
	//     //console.info('高精度数字计算:'+a+operation+b);
	//     let result;

	//     a = (a*10000).toFixed(2);
	//     b = (b*10000).toFixed(2);
	//     a=that.formatN(a,0,false);
	//     b=that.formatN(b,0,false);
	//     if(operation=='+'){
	//         result=(a+b)/10000;
	//     }
	//     if(operation=='-'){
	//         result=(a-b)/10000;
	//     }
	//     if(operation=='*'){
	//         result=(a*b)/100000000;
	//     }
	//     if(operation=='/'){
	//         result=(a/b)/100000000;
	//     }
	//     console.log((a/10000)+operation+(b/10000)+'计算结果 ：'+result);
	//     //result=_this.formatN(result,5,false);
	//     return result;
	// },
	// formatN(v,l,is45){
	//     //要格式化的数字，要保留的小数点后几位，是否要4舍5入
	//     if(v=='' || v==undefined){return 0; return false;}
	//     let zeroLen='0';
	//     for (let i = 1; i < l; i++) {
	//         zeroLen=zeroLen+'0';
	//     }
	//     let vs;
	//     if(is45){
	//         vs=numeral(v).format('0.'+zeroLen);
	//         for (let i = 1; i < l; i++) {
	//             if(this.right(vs,1)=='0'){vs=this.left(vs,vs.length-1);}
	//         }
	//     }else{
	//         vs=v.toString();
	//         if(vs.indexOf('.')>0){
	//             vs=vs.substr(0,vs.indexOf('.'))+'.'+vs.substr(vs.indexOf('.')+1,l);
	//         }
	//         vs=parseFloat(vs);
	//     }
	//     return vs;


	// },
	// left(mainStr,lngLen){
	//     if(lngLen>0){return mainStr.substring(0,lngLen)}
	//     else{return null}
	// },
	// right(mainStr,lngLen){
	//     //alert(mainStr.length)
	//     if(mainStr.length-lngLen>=0 && mainStr.length>=0 && mainStr.length-lngLen<=mainStr.length){
	//         return mainStr.substring(mainStr.length-lngLen,mainStr.length)}
	//     else{return null}
	// },
	// mid(mainStr,starnum,endnum){
	//     if(mainStr.length>=0){
	//         return mainStr.substr(starnum,endnum)
	//     }else{return null}
	//     //mainStr.length
	// }


}